var ApplyManage = require('../../models/user/applyManage')
var User = require('../../models/user/user')

module.exports = {
    add: function(req, res) {
        var body = req.body

        User.findById(body.handler.id, function(err, user) {
            if (err) {
                console.log('userController applyManage fail. err = ' + err)
                return res.json({code: 177, msg: '提交失败'})
            }
            if (!user) {
                return res.json({code: 122, msg: '未找到用户信息'})
            }
            if (user.identity > 0) {
                return res.json({code: 112, msg: '已经是管理了，无需申请'})
            }
            new ApplyManage(body).save(function (err) {
                if (err) {
                    console.log('userController applyManage fail. err = ' + err)
                    return res.json({code: 177, msg: '申请失败'})
                }
                return res.json({code: 100, msg: '申请成功'})
            })
           
        })
    },
    getList: function (req, res) {

        var skip = + req.params.skip
        var limit = + req.params.limit

        var status = + req.query.status

        var filter = {}

        if (status) {
            filter.status = status
        }

        ApplyManage.find(filter).skip(skip).limit(limit).exec(function (err, applys) {
            if (err) {
                console.log('applyManageController getList fail. err = ' + err)
                return res.json({code: 177, msg: '获取失败'})
            }
            if (!applys.length) {
                return res.json({code: 112, msg: '未找到数据'})
            }
            return res.json({code: 100, data: {list: applys}})
        })

    },
    update: function (req, res) {

        var id = req.params.id

        var access = + req.body.access

        var filter = {_id: id}

        var update = {
            status: 1,
            access: access
        }

        ApplyManage.findOneAndUpdate(filter, update, {upsert: true, new: true}, function (err, apply) {
            if (err) {
                console.log('applyManageController update fail. err = ' + err)
                return res.json({code: 177, msg: '更新失败'})
            }
            
            User.findOneAndUpdate({_id: apply.handler.id}, {identity: access}, function (err, user) {
                if (err) {
                    console.log('applyManageController update fail. err = ' + err)
                    return res.json({code: 177, msg: '更新失败'})
                }
                return res.json({code: 100, msg: '更新成功'})
            })
            
        })
        
    }
}